package httpx

import (
	"context"
	"fmt"
	"gitee.com/whilew/cream/pkg/basic_component/log"
	"gitee.com/whilew/cream/pkg/basic_component/orm"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/http"
	"runtime"
)

func Middleware_SetReqId() gin.HandlerFunc {
	return func(c *gin.Context) {
		req_id := uuid.New().String()
		c.Set("req_id", req_id)
		c.Writer.Header().Add("req_id", req_id)
	}
}
func GetReqId(c *gin.Context) string {
	return c.MustGet("req_id").(string)
}
func GetLoger(c *gin.Context) *log.Loger {
	return log.WithKV("req_id", GetReqId(c))
}
func GetOrm(c *gin.Context) *gorm.DB {
	ctx := context.WithValue(context.Background(), "req_id", GetReqId(c))
	return orm.GetDB().WithContext(ctx)
}

// 处理跨域请求,支持options访问
func Middleware_Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.GetHeader("Origin")
		if origin == "" {
			origin = "*"
		}
		c.Header("Access-Control-Allow-Origin", origin)
		c.Header("Access-Control-Allow-Headers", c.GetHeader("Access-Control-Request-Headers"))
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		// 放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}

// panic处理
func Middleware_Recover(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			const size = 64 << 10
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)]
			GetLoger(c).WithKV("req_id", GetReqId(c)).Error(fmt.Sprintf("http_panic err=%+v stack=%s", err, string(buf)), "module", "http_panic")
			c.AbortWithStatusJSON(500, err)
		}
	}()
	c.Next()
}
